package com.grm.common.aspect;

import com.grm.common.enums.ErrorEnum;
import com.grm.common.exception.BusinessException;
import com.grm.common.utils.JwtUtil;
import com.grm.common.annotation.HasPerm;
import com.grm.sys.service.SysPermService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

/**
 * desc: 权限切面实现
 *
 * @author gaorimao
 */
@Aspect
@Component
@Slf4j
public class SysPermAspect {
    @Autowired
    private SysPermService sysPermService;
    @Autowired
    private JwtUtil jwtUtil;

    @Pointcut("@annotation(com.grm.common.annotation.HasPerm)")
    public void pointcut() {
    }

    /**
     * desc: 前置通知，记录controller层操作
     *
     * @param joinPoint 切入点
     */
    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            HasPerm annotation = method.getAnnotation(HasPerm.class);
            if (annotation == null) {
                return;
            }
            // 获取到此接口上需要的权限
            String value = annotation.value();
            // 获取当前用户的所有权限字符列表
            List<String> perms = sysPermService.queryButtonPermList(jwtUtil.getUserId());
            // 用户未授权
            if (!perms.contains(value)) {
                throw new BusinessException(ErrorEnum.UN_AUTHENTICATION);
            }
        }
    }
}
